import json, logging, uuid
from hellowuziqi.service import MapService
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

logging = logging.getLogger('django')

services = {}

@csrf_exempt
def start(request):
    compertition_id = str(uuid.uuid1())
    response = HttpResponse(json.dumps({'msg':'success'}), content_type='application/json')
    response.set_cookie('uuid', compertition_id)
    service = MapService(compertition_id)
    logging.info('游戏已开始！')
    services[compertition_id] = service
    logging.info(compertition_id)
    return response

@csrf_exempt
def down(request):
    uuid = request.COOKIES['uuid']
    service = services[uuid]
    if request.POST:
        cell_x = int(request.POST['cellX'])
        cell_y = int(request.POST['cellY'])
    response_data = {}
    if(service.is_down([cell_x, cell_y]) == None and cell_x > 0 and cell_x <= service.cell_line and cell_y > 0 and cell_y <= service.cell_line):
        service.user_cells.append([cell_x, cell_y])
        robot_is_down = False
        while (not robot_is_down):
            is_random, cell = service.get_cell()
            robot_is_down = True
        response_data['cellX'] = cell[0]
        response_data['cellY'] = cell[1]
        service.robot_cells.append(cell)
        victory = None
        if(service.is_victory(service.user_cells)):
            victory = 'user'
        elif(service.is_victory(service.robot_cells)):
            victory = 'robot'
        if(victory != None):
            robot_victory = victory == 'robot'
            response_data['victory'] = victory
            logging.info('游戏已结束！')
            if(is_random):
                service.save(service.user_cells, service.robot_cells, robot_victory)
                logging.info('对局已记录！')
            service.clear()
            services.pop(uuid)
    logging.info({'user':service.user_cells, 'robot':service.robot_cells})
    return HttpResponse(json.dumps(response_data), content_type='application/json')

@csrf_exempt
def end(request):
    uuid = request.COOKIES['uuid']
    try:
        services[uuid].clear()
        services.pop(uuid)
    except KeyError as e:
        logging.error(e)
    return HttpResponse(json.dumps({'msg':'success'}), content_type='application/json')
